<?php

// For the retrive data
// http://ws.spexlive.net/service/rest/catalog?method=getProduct&appId=223252&skuNumberType=Ingram%20Micro%20USA&skuNumberVal=V28145&catalog=na&descriptionTypes=all&skuTypes=all&accessoryMax=0&displayTemplate=0&resourceType=all

class Maven_ManageCatalogSpr_Model_ProductSave extends Maven_ManageCatalogSpr_Model_ProductImport
//Varien_Object
{
	/**
	 * input data
	 * @var array;
	 */
	public $data;
	/**
	 * Product save Row Data.
	 * @var array
	 */
	public $rowData;

	public $sku;
	public $productId;
	public $mpn;
	public $etPid;

	public $rowNo;

	public $logMsg = array();


	public $print_str = '';

	public $attrib_set;


	public $cat_id;

	protected $_xmlObj;
	protected $_tables;
	//protected $_varchar_attrib = array();

	public $errorResponse =false;

	public function __construct()
	{
		parent::__construct();
	}
	public function loadProduct($pArray)
	{
		//$this->sku = $pArray['sku'];
		$this->id = $pArray['id'];
        $this->loadDataString();
		$this->rowData = array();

	}

	public function setMessage($msg)
	{
		$this->logMsg[] = $msg;
	}

	public function writeLog()
	{
		$this->logMsg[] = $this->print_str;

		if(count($this->logMsg) > 0) {
			if(is_array($this->logMsg)) {
				$message = "Rowid: ".$this->rowNo."  SKU: ".$this->sku.'\n'.implode("\n",$this->logMsg);
				return $message;
				//Mage::log($message, 7, $this->getConfigVal('log_file'));
			}
		}
	}
	public function loadDataString()
	{
		//$sku = $this->sku;
		$this->mpn = '';

		$id  = $this->id;
		
		if($id  != '') {
			$this->importLogRow = Mage::getModel('managecatalogspr/importlog')->load($id);
           	$this->sku = trim($this->importLogRow->getSku());
			$this->rowNo = trim($this->importLogRow->getId());
            
            if($this->rowNo==1) {
				if(!$this->attrib_set = $this->getCurrentAttributeSet()) { // Default Attribute Set
					$this->setMessage('Attribute Set id not selected!');
					return false;
				}
				//add attributes
				$this->loadAttrib('Etilize Pid','','','e_',array('visible_on_front'=>false));
				$this->loadAttrib('weight','','','',array('visible_on_front'=>true));
				$this->loadAttrib('UPC','','','');
				$this->loadAttrib('MPN','','','');
				$this->loadAttrib('Google Base Payment Note','','','e_',array('visible_on_front'=>false));
				$this->loadAttrib('Google Base Condition','','','e_',array('visible_on_front'=>false));
			}
		}
       	if(count($this->importLogRow->getData())>0) {
			if($this->importLogRow->getEstatus() != 1) {
				$this->data 	= $this->getRowData($this->importLogRow->getStr());
				$this->mpn 		= str_replace(' ','',$this->data[2]);
				$this->setXmlData();
				//print_r(count($this->_xmlObj->type));
				//exit;
				if($this->_xmlObj->getName() == 'ErrorResponse') {
					$this->setMessage((string) $this->_xmlObj->type. " : ". (string) $this->_xmlObj->message);
					 $this->errorResponse=true;
					//unset($this->data);
					//unset($this->mpn);
				}else {
					foreach ($this->_xmlObj->attributes() as $ele) {
						if($ele->getName() == 'productId') {
							$this->etPid = (string) $ele;
						}
					}
				}

			} else {
				$this->print_str = "PreUpdated";
			}
		}else {
			$this->data 	= array();
			$this->setMessage("Data Not Exist!");
			$this->print_str = "Data Not Exist!";
		}

	}
	public function getRowData($rowString)
	{
		$data = explode('","',substr(trim($rowString),1, -1));
       	$new_data = array();
		if(is_array($data)){
			for($i=0; $i<count($data); $i++) {
				$item1 = trim($data[$i]);
				$item1 = trim($item1,'"');
				$new_data[$i] = $item1;
			}
			//array_walk($data, 'trim_data');
		}
		return $new_data;
	}
	public function addGeneralAttrbutes($attribSet, $installer)
	{
		//$installer->installDefaultGroupIds();
		$defaultSet = $this->getAttributeSet('Default');
		$defGroups = array('General','Prices','Meta Information','Images','Design');

		foreach ($defGroups as $groupName) {

			//assign default group to Attribute set
			$groupRow = $installer->getAttributeGroup($this->getEntityTypeId(), $defaultSet->getAttributeSetId(), $groupName);
			if(count($groupRow)>0) {
					
				//if($groupName != 'General')
				$this->loadAttributeGroup($groupName,$attribSet);

				$groupObj = $installer->getAttributeGroup($this->getEntityTypeId(), $attribSet->getAttributeSetId(), $groupName);

				//assign default attribute to default attribute group
				/*
				 $product = Mage::getModel('catalog/product');
				 $product->setAttributeSetId($defaultSet->getAttributeSetId());
				 $prod_attribs = $product->getAttributes($groupRow['attribute_group_id'], false);
				 */
				//retrive default attribute set Id result set
				$prod_attribs = $this->getAllAttributeIds($this->getEntityTypeId(), $defaultSet->getAttributeSetId(), $groupRow['attribute_group_id']);

				foreach($prod_attribs as $attrib) {
					//print $attrib->getData('attribute_id');
					$installer->addAttributeToSet($this->getEntityTypeId(), $attribSet->getAttributeSetId(), $groupObj['attribute_group_id'], $attrib['id']);
				}
			}
		}
	}
	public function getAllAttributeIds($entityTypeId, $setId, $groupId)
	{
		$atIds = $this->con->query("SELECT attribute_id as id FROM eav_entity_attribute
				WHERE entity_type_id='".$entityTypeId."' AND attribute_set_id='".$setId."' 
				AND attribute_group_id='".$groupId."' ORDER BY sort_order ASC ")->fetchAll();
		return $atIds;
	}
	public function getAttributeSet($set='')
	{
		$installer = new Mage_Catalog_Model_Resource_Eav_Mysql4_Setup('core_setup');
		$attributeSet = new Varien_Object($installer->getAttributeSet($this->getEntityTypeId(), $set));
		if($attributeSet->hasData()) {
			return $attributeSet;
		}else {
			return false;
		}
	}
	public function getCurrentAttributeSet()
	{
		
		$set = $this->getAttributeSetName();

		if($attribSet = $this->getAttributeSet($set)) {
			if($set!='Default') {
				$installer = new Mage_Catalog_Model_Resource_Eav_Mysql4_Setup('core_setup');
				$installer->addAttributeSet($this->getEntityTypeId(), $set, 0);
				$attribSet = $this->getAttributeSet($set);
				$this->addGeneralAttrbutes($attribSet, $installer);
			}
			return $attribSet;
		} else {
			 
			$installer = new Mage_Catalog_Model_Resource_Eav_Mysql4_Setup('core_setup');
			$installer->addAttributeSet($this->getEntityTypeId(), $set, 0);
			$attribSet = $this->getAttributeSet($set);
			$this->addGeneralAttrbutes($attribSet, $installer);
			return $attribSet;
		}
		return false;
	}
	public function getXmlByUrl($urlString)
	{
		$xmlstr1='';
		$fp1 = fsockopen ("ws.spexlive.net", 80, $errno, $errstr, 30);
		if (!$fp1)	{
			return false;
		}
		else	{
			fputs ($fp1, "GET $urlString HTTP/1.0\r\nHost: ws.spexlive.net\r\n\r\n");
			while (!feof($fp1)) {
				$xmlstr1.= fgets ($fp1,1248);
			}
			fclose ($fp1);
			
			$xmlstr1=utf8_encode($xmlstr1);
					
			$s1=explode("?>",$xmlstr1);
			$rs=$s1[1];
			$xm=new SimpleXMLElement($rs);
			return $xm;
		}
	}
	public function setXmlData()
	{ 
	    $url = "http://ws.spexlive.net/service/rest/catalog?method=getProduct&appId=".$this->getAppId()."&skuNumberType=SP%20Richards&skuNumberVal=".$this->sku."&catalog=na&descriptionTypes=all&skuTypes=all&accessoryMax=0&displayTemplate=0&resourceType=all";
        $this->_xmlObj = $this->getXmlByUrl($url);
        
	}
	public function getXmlData()
	{
		return $this->_xmlObj;
	}
	public function getSimpleXML($urlString)
	{
		try {
			$fp1 = fsockopen ("ws.spexlive.net", 80, $errno, $errstr, 30);
			if (!$fp1)	{
				return false;
			}
			else	{
				fputs ($fp1, "GET $urlString HTTP/1.0\r\nHost: ws.spexlive.net\r\n\r\n");
				while (!feof($fp1)) {
					$xmlstr1.= fgets ($fp1,1248);
				}
				fclose ($fp1);
				$xmlstr1=utf8_encode($xmlstr1);
				return $xmlstr1;
			}
		}catch (Exception $e) {
			$this->setMessage($e->getMessage());
		}
	}

	public function checkImage()
	{
		$isimage="n";
		if(count($this->_xmlObj->resources)==0) {
			$this->setMessage("Image url not found!");
			return $isimage;
		} else	{
			$skc=count($this->_xmlObj->resources->children());

			for($j=0;$j < $skc;$j++) {
				$sk1=(string)$this->_xmlObj->resources->resource[$j]['type'];
				$sk2=(string)$this->_xmlObj->resources->resource[$j]['status'];

				if((string)$this->_xmlObj->resources->resource[$j]['url']) {
					if(in_array($sk1,array('300','Large','160','Thumbnail')) && $sk2=="Published") {
						if($sk1 == 'Thumbnail') {
							$i_name = 'e_etilize_image';
						}else {
							$i_name = 'e_etilize_image_'.strtolower($sk1);
						}
						$this->rowData[$i_name] = (string)$this->_xmlObj->resources->resource[$j]['url'];
					}
				}
				/*
				 $this->loadAttrib('et_image_large');
				 $this->loadAttrib('et_image');
				 $this->loadAttrib('et_image_300');
				 $this->loadAttrib('et_image_160');
				 */
				if($sk1=="Thumbnail" &&  $sk2=="Published") {
					$isimage="y";
				}

			}
			if($isimage=="y") {
				return "y";
			} else {
				return "n";
			}

		}
	}

	public function formatUrlKey($string)
	{
		$new = trim(strtolower($string));
		$new = preg_replace("/[^a-zA-Z0-9\s]/", "-", $new);
		$new = str_replace(" ","-",$new);
		return $new;
	}


	public function setDetails()
	{
		try {
			if(count($this->_xmlObj->descriptions)==0) {
				$this->setMessage("Error from retriving Product Details on Spexlive.net");
				return;
			} else	{
				$c=0;
				if(isset($this->_xmlObj->descriptions)) {
					$m=	$this->_xmlObj->descriptions;
					@$c=count($m->children());
				}
				$desc = '';
				for($k=0;$k<$c;$k++) {
					if($m->description[$k]['type']==2) {
						$this->rowData['name'] = (string) htmlentities($m->description[$k], ENT_QUOTES, "utf-8" );
						$this->rowData['meta_title'] = $this->rowData['name'];
						$this->rowData['url_key']    = $this->formatUrlKey($this->rowData['name']);
					}
					if($m->description[$k]['type']==1) {
						$this->rowData['description'] =  (string) $m->description[$k];
						$desc .= $this->rowData['description'].", ";
					}
					if($m->description[$k]['type']==3) {
						$this->rowData['short_description'] = (string) $m->description[$k];
						$desc .= $this->rowData['description'];
					}
				}

				if(strlen(trim($desc))>0) {
					$this->rowData['meta_description'] 	= $desc;
					$this->rowData['meta_keyword'] 		= $desc;
				}
			}
		}catch (Exception $e) {
			$this->setMessage("Error in Detail data".$e->getMessage());
		}
	}
	public function getProductSummaryId($productSummary)
	{
		$i=0;
		$sFlag=0;
		$mFlag=0;
		foreach ($productSummary  as $ps) {
			foreach($ps->skus->sku as $sku) {
				if((string) $sku->attributes()->number == $this->sku) {
					$sFlag=1;
				}
				if((string) $sku->attributes()->number == $this->mpn ) {
					$mFlag=1;
				}
				if($sFlag==1 && $mFlag==1) {
					$this->etPid = (string) $ps->attributes()->id;
					return $i;
				}
			}
			$i++;
		}

		$i=0;
		$sFlag=0;
		$mFlag=0;
		foreach ($productSummary  as $ps) {
			foreach($ps->skus->sku as $sku) {
				if((string) $sku->attributes()->number == $this->sku) {
					$sFlag=1;
				}
				if((string) $sku->attributes()->number == $this->mpn ) {
					$mFlag=1;
				}
				if($sFlag==1 || $mFlag==1) {
					$this->etPid = (string) $ps->attributes()->id;
					return $i;
				}
			}
			$i++;
		}
		return '';
	}
	public function getPId()
	{
		if($this->etPid!='') {
			return $this->etPid;
		} else {
			$this->setMessage("Product Id not found for the Attributes!");
			return false;
		}
	}
	public function loadAttributeGroup($group, $attribSet='')
	{
		$setup = new Mage_Eav_Model_Entity_Setup('core_setup');
		if($attribSet!='') {
			$group_ob = $setup->addAttributeGroup($attribSet->getEntityTypeId(),$attribSet->getAttributeSetId(), $group);
		}else if(isset($this->attrib_set)) {
			$group_ob = $setup->addAttributeGroup($this->getEntityTypeId(), $this->attrib_set->getAttributeSetId(), $group);
		}else {
			return false;
		}
		return $group_ob;
	}
	public function formatAttribName($attrib = '', $prefix = "e_")
	{
		$set = $this->getAttributeSetName();
		if($set!='Default')
		$attrib = $set."_".$attrib;
			
		$attrib = strtolower((string) $attrib);
		$str = preg_replace("/[^a-zA-Z0-9]+/", "_", $attrib);

		$str = str_replace(" ","_",$str);
		return $prefix.$str;
	}

	public function getAttributeDataType($attrib)
	{
		$attrib = strtolower((string) $attrib);
		$str = preg_replace("/[^a-zA-Z0-9\s]/", "_", $attrib);
		$str = str_replace(" ","_",$str);
		if(in_array($str,$this->_varchar_attrib)) {
			return true;
		}else {
			return false;
		}
	}
	/**
	 * Get table name
	 *
	 * @param string $tableName
	 * @return string
	 */
	public function getTable($tableName) {
		if (!isset($this->_tables[$tableName])) {
			$this->_tables[$tableName] = Mage::getSingleton('core/resource')->getTableName($tableName);
		}
		return $this->_tables[$tableName];
	}

	public function getAttrributeId($code)
	{
		if($code) {
			$installer = new Mage_Catalog_Model_Resource_Eav_Mysql4_Setup('core_setup');
			$attributeId = $installer->getAttributeId('catalog_product', $code);
			return $attributeId;
		}else return "";
	}

	public function createCustomAttrib($code,$array)
	{
		$installer = new Mage_Catalog_Model_Resource_Eav_Mysql4_Setup('core_setup');
		$installer->startSetup();
		$installer->addAttribute('catalog_product', $code , $array);
		if($groupId=='') {
			$groupId = $installer->getDefaultAttributeGroupId('catalog_product', $this->attrib_set->getAttributeSetId());
		}
		if($groupId != '') {
			$installer->addAttributeToSet('catalog_product', $this->attrib_set->getAttributeSetId(), $groupId, $attributeId);
		}
		$installer->endSetup();
		unset($installer);
	}

	public function attribArray()
	{
		return $array = array(
			'backend_model'             => 'backend',
            'backend_type'              => 'type',
            'backend_table'             => 'table',
            'frontend_model'            => 'frontend',
            'frontend_input'            => 'input', 
            'frontend_input_renderer'   => 'input_renderer', 
            'frontend_label'            => 'label', 
            'frontend_class'            => 'frontend_class', 
            'source_model'              => 'source', 
            'is_global'                 => 'global', 
            'is_visible'                => 'visible',
            'is_required'               => 'required',
            'is_user_defined'           => 'user_defined',
            'default_value'             => 'default', 
            'is_searchable'             => 'searchable', 
            'is_filterable'             => 'filterable', 
            'is_comparable'             => 'comparable', 
            'is_visible_on_front'       => 'visible_on_front', 
            'is_html_allowed_on_front'  => 'is_html_allowed_on_front', 
            'is_visible_in_advanced_search' => 'visible_in_advanced_search',
            'is_used_for_price_rules'   => 'used_for_price_rules', 
            'is_filterable_in_search'   => 'filterable_in_search', 
            'used_in_product_listing'   => 'used_in_product_listing',
            'used_for_sort_by'          => 'used_for_sort_by', 
            'is_unique'                 => 'unique', 
            'apply_to'                  => 'apply_to', 
            'is_configurable'           => 'is_configurable', 
            'note'                      => 'note', 
            'position'                  => 'position'
            );
	}
	/**
	 * Create attributes if not exist,
	 * If the attribute is exist and the group is not defined, it will defined their
	 * group.
	 */
	public function loadAttrib($attrib,$groupId='', $value='', $prefix='e_', $params = array())
	{
		try {
		  
        	$code = $this->formatAttribName($attrib,$prefix);
			$filterable = false;
			if(strlen($value) > 254) {
				$type = 'text';
				$input = 'textarea';
			}else if(strlen($value) != strlen(strip_tags($value))) {
				$type = 'varchar';
				$input = 'text';
			}else if($attrib == 'MPN' || $attrib == 'UPC' || $attrib == 'Etilize Pid' || $attrib == 'Google Base Payment Note' || $attrib == 'Google Base Condition' ) {	
				$type = 'varchar';
				$input = 'text';
			}else {
				$type = 'int';
				$input = 'select';
				//$filterable = true;
			}
            
            if($attrib == '')


			//$installer = new Mage_Catalog_Model_Resource_Eav_Mysql4_Setup('core_setup');
			$this->installer->startSetup();
			$at_ob = Mage::getModel('eav/entity_attribute')->loadByCode('catalog_product', $code);
			if(count($at_ob->getData()) > 0) {
					
				//if($at_ob->getData('is_filterable') == '1' && $at_ob->getData('backend_type') == 'int' && $at_ob->getData('frontend_input') == 'select') {
				// Do not Update the attrib..
				$attributeId =  $at_ob->getAttributeId();
				if(count($params)>0) {
					$a_ar = $this->attribArray();
					foreach($params as $key => $val) {
						$fld =  array_search($key, $a_ar);
						//if($fld!='is_filterable' && $fld != 'is_filterable_in_search') {
						//$installer->updateAttribute('catalog_product', $code , $fld, $val);
						//}
					}
				}
			}else {
				$param_ar = array(
			        'type'              => $type,
			        'backend'           => '',
			        'frontend'          => '',
			        'label'             => $attrib,
			        'input'             => $input,
			        'class'             => '',
			        'source'            => '',
			        'global'            => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL,
			        'visible'           => true,
			        'required'          => false,
			        'user_defined'      => true,
			        'default'           => '',
			        'searchable'        => false,
			        'filterable'        => $filterable,
			        'comparable'        => false,
			        'visible_on_front'  => true,
			        'unique'            => false,
			        'apply_to'          => '',
			        'is_configurable'   => false,
					'is_html_allowed_on_front' => true
				);
				foreach($params as $key => $val) {
					$param_ar[$key] = $val;
				}
				$this->installer->addAttribute($this->getEntityTypeId(), $code , $param_ar);
				$attributeId = $this->installer->getAttributeId('catalog_product', $code);

				$this->installer->updateAttribute($this->getEntityTypeId(), $code, 'is_html_allowed_on_front', 1);
				$this->installer->updateAttribute($this->getEntityTypeId(), $code, 'is_searchable', 0);


				// update operation for the specific attributes
				/*if(in_array($attrib, $this->disable_layer_nav)) {
					$this->installer->updateAttribute($this->getEntityTypeId(), $code, 'is_filterable', 0);
					$this->installer->updateAttribute($this->getEntityTypeId(), $code, 'is_filterable_in_search', 0);
					}*/

				/*
				 if($code == 'e_actual_screen_size') {
				 $installer->updateAttribute($this->getEntityTypeId(), $code, 'label', 'Screen Size');
				 }
				 */



				if($groupId=='') {
					$groupId = $this->installer->getDefaultAttributeGroupId($this->getEntityTypeId(), $this->attrib_set->getAttributeSetId());
				}
				/*echo $groupId;
				 echo " ST: ".$this->attrib_set->getId()." GR: ". $groupId." AT: ". $attributeId;
				 //exit;*/


				/*
				 $installer->updateAttribute('catalog_product', $code, 'is_searchable', 1);
				 $installer->updateAttribute('catalog_product', $code, 'is_filterable', 1);
				 $installer->updateAttribute('catalog_product', $code, 'is_filterable_in_search', 1);
				 $installer->updateAttribute('catalog_product', $code, 'is_visible_on_front', 1);
				 */
			}

			if($code == 'e_etilize_pid') {
				$groupId = $this->installer->getDefaultAttributeGroupId($this->getEntityTypeId(), $this->attrib_set->getAttributeSetId());
				$this->installer->addAttributeToSet($this->getEntityTypeId(), $this->attrib_set->getAttributeSetId(), $groupId, $attributeId);
			} else if($groupId != '') {
				$this->installer->addAttributeToSet($this->getEntityTypeId(), $this->attrib_set->getAttributeSetId(), $groupId, $attributeId);
			}
			$this->installer->endSetup();
				
			//unset($installer);
			return $attributeId;
		}catch (Exception $e) {
			die($e->getMessage());
			$this->setMessage("Attribute Load Error: ".$e->getMessage());
		}
	}
	public function getAttributeValue($code, $value)
	{
		//print $code.":".$value;
		$at_ob = Mage::getModel('catalog/product')->getResource()->getAttribute($code);
		if($at_ob->getData('backend_type') == 'int' && $at_ob->getData('frontend_input') == 'select') {
			//print $code.":".$value."\n";	
			return $this->getAttributeOptionId($code, $value);
		}else {
			//print "value".$value ."\n";
			return $value;
		}
	}
	public function setAttributesData()
	{
		try {
			if($this->getPId()) {
				$this->rowData['e_etilize_pid'] = $this->getPId();
				if(count($this->_xmlObj->datasheet)==0) {
					$this->setMessage("Error from retriving Attributes on Spexlive.net");
					return;
				} else	{
					if(@count($this->_xmlObj->datasheet->children())) {

						$installer = new Mage_Catalog_Model_Resource_Eav_Mysql4_Setup('core_setup');
						foreach($this->_xmlObj->datasheet->attributeGroup as $group) {


							$attrib_group = $this->loadAttributeGroup((string) $group['name']);

							$groupResult = $installer->getAttributeGroup($this->getEntityTypeId(), $this->attrib_set->getAttributeSetId(), (string) $group['name']);
							$groupId='';
							if(count($groupResult)>0)
							$groupId = $groupResult['attribute_group_id'];


							if($groupId!='') {
								for($i=0; $i < count($group->children());$i++) {
									$code = (string) $group->children()->attribute[$i]['name'];
									$code_value = (string) (string) $group->children()->attribute[$i];

									if($group['id'] == 35 && $code == "Manufacturer") {
										$this->rowData['manufacturer'] = $this->getMfgId($code_value);
									}else if($group['id'] == 35 && $code=="Manufacturer Part Number") {
										$this->rowData['mpn'] = $code_value;
									}else {
										//create the attribute if not exist.
										$Params = array();
										/*
										 if(strlen($code_value) < 255 || strlen($code_value) == strlen(strip_tags($code_value))) {
											$Params = array('input'=>'select','type'=>'int','filterable'=>true, 'filterable_in_search'=> true);
											}
											*/

										$this->loadAttrib($code, $groupId, $code_value,'e_', $Params);
										$this->rowData[$this->formatAttribName($code)] = $this->getAttributeValue($this->formatAttribName($code), $code_value);
									}
									//$this->makeIndices($this->store->getId(), $this->productId, $this->getAttrributeId($code), $code_value );
								}
							}
						}
					}
				}
			}
		}catch (Exception $e) {
			$this->setMessage("Error in Attribute data".$e->getMessage());
		}
	}
	public function addProductIndex()
	{
		$product = Mage::getModel('catalog/product')->setStoreId($this->store->getStoreId())->setWebsiteId($this->websiteIds)
		->load($this->productId);
		$obj = Mage::getModel('catalogindex/indexer');
		$this->_runIndexingProcess($product, $reindexType);
	}
	public function makeIndices($storeId, $entityId, $attributeId, $value, $type='')
	{
		//Price indices
		$value = mysql_escape_string($value);
		if($type == 'price') {
			foreach($this->websiteIds as $website_id) {
				$check = $this->con->query("SELECT * FROM catalogindex_price
				WHERE entity_id='".$entityId."' AND attribute_id='".$attributeId."' 
				AND website_id='".$website_id."'")->fetchAll();
				if(count($check)>0) { //update
					$p_sql = $this->con->query("UPDATE catalogindex_price
						SET customer_group_id = 0, qty = 0, value = '".$value."', 
						tax_class_id='0'  
						WHERE entity_id='".$entityId."' AND attribute_id='".$attributeId."' 
						AND website_id='".$website_id."'");	
				}else { //insert
					$p_sql = $this->con->query("INSERT INTO catalogindex_price
					(entity_id,attribute_id, customer_group_id, qty , value, tax_class_id,website_id)  
					VALUES
					('".$entityId."', '".$attributeId."', '0', '0', '".$value."', '0', '".$website_id."')"); 
				}
			}
		}else {
			$check = $this->con->query("SELECT * FROM catalogindex_eav
			WHERE entity_id='".$entityId."' AND attribute_id='".$attributeId."' 
			AND store_id='".$storeId."'")->fetchAll();
			if(count($check)>0) { //update
				$p_sql = $this->con->query("UPDATE catalogindex_eav
					SET value = '".$value."' 
					WHERE entity_id='".$entityId."' AND attribute_id='".$attributeId."' 
					AND store_id='".$storeId."'");	
			}else { //insert
				$p_sql = $this->con->query("INSERT INTO catalogindex_eav
				(entity_id,attribute_id, value, store_id)  
				VALUES
				('".$entityId."', '".$attributeId."', '".$value."', '".$storeId."')"); 
			}
		}
	}
	/**
	 * get manufacturer id from the manufracture name
	 */
	public function getMfgId($vendor)
	{
		$vendor = mysql_escape_string($vendor);
		$pRes = Mage::getModel('catalog/product')->getResource()->getAttribute('Manufacturer');
		$value = '';
		if($vendor!= '') {
			$sel_res = $this->con->query("SELECT
				o.option_id, v.value_id FROM eav_attribute_option_value v
LEFT JOIN eav_attribute_option o ON o.option_id = v.option_id  
WHERE v.store_id = '".$this->store->getStoreId()."' AND LOWER(v.value) = LOWER('".$vendor."') ")->fetchAll();
			if(count($sel_res)>0) {
				$value = $sel_res[0]['option_id'];
			}else {
				$stmt = $this->con->prepare("INSERT INTO `eav_attribute_option`
				(`option_id`, `attribute_id`, `sort_order`) VALUES (NULL, '".$pRes->getAttributeId()."', '0')"); 
				$stmt->execute();
				$opt_id = $this->con->lastInsertId();
				$value = $opt_id;
				foreach ($this->_stores as $store) {
					$stmt = $this->con->prepare("INSERT INTO `eav_attribute_option_value`
						(`value_id`, `option_id`, `store_id`, `value`) 
						VALUES (NULL, $opt_id, '".$store->getStoreId()."', '".$vendor."') "); 
					$stmt->execute();
				}
			}
		}
		return $value;
	}
	public function getAttributeOptionId($code, $data)
	{
		try {
			//$data = mysql_escape_string($data);
			$pRes = Mage::getModel('catalog/product')->getResource()->getAttribute($code);
			$opt_id = '';

			$optionTable        = $this->getTable('eav/attribute_option');
			$optionValueTable   = $this->getTable('eav/attribute_option_value');
                        
			if($data!= '') {
				    /*
				    $sel_res = $this->con->query("SELECT
					o.option_id, v.value_id FROM eav_attribute_option_value v
					LEFT JOIN eav_attribute_option o ON o.option_id = v.option_id
					WHERE v.store_id = '".$this->store->getStoreId()."' AND LOWER(v.value) = LOWER('".$data."') ")->fetchAll();
					*/
				$select = $this->con->select()
					->from(array('main' => $optionValueTable))
					->join(
					array('option' => $optionTable),
							'main.option_id=option.option_id',array('main.option_id'))
					->where("main.store_id=?", $this->store->getStoreId())
					->where("LOWER(main.value)=?", strtolower($data))
					->where("option.attribute_id=?",$pRes->getAttributeId());
				$sel_res = $this->con->fetchRow($select);
			    
				if(isset($sel_res['option_id'])) {
					$opt_id = $sel_res['option_id'];
			
				}else {
					/*
					 $stmt = $this->con->prepare("INSERT INTO `eav_attribute_option`
					 (`option_id`, `attribute_id`, `sort_order`) VALUES (NULL, '".$pRes->getAttributeId()."', '0')");
					 $stmt->execute();
					 */
					$insData = array(
							'attribute_id'  => $pRes->getAttributeId(),
							'sort_order'    => 0,
					);
					
					$this->con->insert($optionTable, $insData);
					$opt_id = $this->con->lastInsertId();
							
					$this->con->delete($optionValueTable, $this->con->quoteInto('option_id=?', $opt_id));
					foreach ($this->_stores as $store) {
						/* 
						 $stmt = $this->con->prepare("INSERT INTO `eav_attribute_option_value`
							(`value_id`, `option_id`, `store_id`, `value`)
							VALUES (NULL, $opt_id, '".$store->getStoreId()."', '".$data."') ");
							$stmt->execute();
							*/
						$dataValue = array(
							'option_id' => $opt_id,
							'store_id'  => $store->getStoreId(),
							'value'     => $data,
						);
						$this->con->insert($optionValueTable, $dataValue);
					}
				}
			}
			return $opt_id;
		}catch(Exception $e) {
			$this->setMessage("Error in Retriving Attribute Option".$code.$e->getMessage());
		}
	}
	public function getAttributeSetName()
	{
		if($this->cat_id!='') {
			$category = Mage::getModel('catalog/category')->load($this->cat_id);
			//if($category->getName()!='')
			return $category->getName();

		}
		return 'Default';
	}
	public function getCategoryId($cat_ref_id)
	{
	    //$data=Mage::getModel('catalog/category')->getCollection()->addAttributeToFilter('sp_catid',$cat_ref_id)->getData();
        $ids= "";
		$res = array();
		$cat_ids = array();
		if($cat_ref_id == '') {
			$ids= "";
		}else {
			$res = $this->con->query("SELECT  entity_id FROM `catalog_category_entity_int`
					WHERE `value`   = '".$cat_ref_id."'")
                    ->fetchAll(PDO::FETCH_COLUMN, 0); 
					/*OR (parent_catid = '".$cat_ref_id."' AND cpu='".$cpu."')")
                    ->fetchAll(PDO::FETCH_COLUMN, 0);*/
		}

		if(count($res) > 0) {
			$cat_ids = array_merge($cat_ids, $res);
		}
		
		if(count($cat_ids) > 0) {
			$this->cat_id = $cat_ids[0];
			$ids= implode(",", $cat_ids);
		}
        return $cat_ids;
		//return $ids;
	}
	public function getFormattedWeight($val) {
		$val=trim($val);
		$w='';
		preg_match('/^(([0-9]*)+(([\.|,])+([0-9]*)|)(\s*)+(lb))/', $val, $lbs);
		preg_match('/^(([0-9]*)+(([\.|,])+([0-9]*)|)(\s*)+(oz))/', $val, $ozs);
		preg_match('/^(([0-9]*)+(([\.|,])+([0-9]*)|)(\s*)+)/', $val, $weight);

		if(isset($ozs[0])) {
			$w = ($weight[0] / 16);
		}else if(trim(is_numeric($val))) {
			$w = $val;
		}
		else { // default lbs
			$w = $weight[0];
		}
		return $w;
	}
	public function getPrice($price)
	{
		if($price>0) {
			$per = $this->getConfigVal('price_markup_percent');
			return $price * (1 + ($per/100));
		}else {
			return 0;
		}
	}

	public function processData()
	{
		try {
			if($this->errorResponse){
                $this->setMessage('Error Response from Spexlive!');
                return false;
            }
			if($this->print_str == 'PreUpdated') {
				$this->setMessage('PreUpdated!');
				return false;
			}
			if(count($this->data) == 0) {
				$this->setMessage('Data reading problem!');
				return false;
			}
			if((is_numeric($this->sku) && $this->sku == 0)) {
				$this->setMessage(Zend_Json::encode($this->data). ' - Data reading problem!');
				return false;
			}
			if(!isset($this->rowNo) || !isset($this->sku) || $this->sku == ''
			|| strlen($this->sku) < 4 || (bool) strpos($this->sku,".")) {
				$this->setMessage(Zend_Json::encode($this->data).' - Data reading problem!');
				return false;
			}

			//category ids
			if($this->data[17]){
                $catid=trim($this->data[17]);
            }else{$catid='';}    
            $cat_id = $this->getCategoryId($catid);

			if(!$this->attrib_set = $this->getCurrentAttributeSet()) {
				$this->setMessage('Attribute Set id not selected!');
				return false;
			}

			//description
			$desc = trim($this->data[8].' '.$this->data[9]);
			
			$productId = Mage::getModel('catalog/product')->getIdBySku($this->sku);
			if ($productId) {
				$product = Mage::getModel('catalog/product')->load($productId);

				foreach ($product->getData() as $key => $val) {
					if($val!= '') {
						$this->rowData[$key] = '';
					}
				}
			}
			else {
				$product = Mage::getModel('catalog/product');
			}

			$this->rowData['sku'] 						= $this->sku;
			$this->rowData['entity_type_id'] 			= $this->getEntityTypeId();
			$this->rowData['attribute_set_id'] 			= $this->attrib_set->getAttributeSetId(); //'Default';
			$this->rowData['type'] 						= 'simple';
			$this->rowData['type_id'] 					= 'simple';

			$this->rowData['category_ids'] 				= $cat_id;
			$this->rowData['has_options'] 				= 0;

			$this->rowData['name'] 						= $this->data[16];
			$this->rowData['description'] 				= $desc;
			$this->rowData['short_description'] 		= $desc;

			$this->rowData['mpn'] 						= $this->data[2];
			$this->rowData['weight'] 					= $this->data[32];
			$this->rowData['manufacturer'] 				= ''; //$this->getMfgId($this->data[2]);

			$this->rowData['visibility'] 				= Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH;

			$this->rowData['url_key'] 					= $this->formatUrlKey($desc);

			$this->rowData['price'] 					= $this->getPrice(($this->data[38] * 0.01)); // * $this->getConfigVal('price_markup_percent'));
			$this->rowData['special_price'] 			= ''; //($this->data[14]);
			$this->rowData['cost'] 						= ($this->data[38] * 0.01);
			$this->rowData['tax_class_id'] 				= 2;
			$this->rowData['upc'] 						= ($this->data[3]);
			$this->rowData['enable_googlecheckout'] 	= 1;
			$this->rowData['google_base'] 				= 1;
			$this->rowData['e_google_base_payment_note'] = 'Google Checkout';
			$this->rowData['e_google_base_condition'] 	= 'New';

			$this->rowData['google_base'] 				= 1;
            $this->rowData['meta_title'] 				= $desc;
			$this->rowData['meta_keyword'] 				= $desc;
			$this->rowData['meta_description'] 			= $desc;
            $this->rowData['active'] 					= 0;

			$this->rowData['website_ids'] 				= $this->websiteIds;

            
			$this->setDetails();
			$this->setAttributesData();
            
			/*echo "<pre>1";
			 print_r($this->rowData);
			 exit; */
			if(isset($this->rowData['e_weight']) && $this->rowData['e_weight'] != '') {
				$this->rowData['weight'] 		= $this->rowData['e_weight'];
			}elseif(isset($this->rowData['e_shipping_weight']) && $this->rowData['e_shipping_weight'] != '') {
				$this->rowData['weight'] 		= $this->rowData['e_shipping_weight'];
			}
			$this->rowData['weight'] = $this->getFormattedWeight($this->rowData['weight']);

			$status=1;
			$is_in_stock=1;
			if ($this->rowData['price'] <= 1 || trim($this->rowData['weight']) == '' || $this->rowData['weight'] <= 0 ) { // || $this->data[16] == 'N') { // if deleted or out of stock.
				$status=1;
				$is_in_stock=0;
			}

			$this->rowData['status'] = $status;
            $this->productId = $productId;

			//Save Product Detail
			$product->setStoreId($this->store->getId());
			//$product->setWebsiteIds(array(1));
			//$product->setWebsiteIds(1);
                
           	$product->setData($this->rowData);
			$product->setStatus($status);

			//$product->setIsMassupdate(true);
			//$product->setExcludeUrlRewrite(true);
			
			/* echo "<pre>1";
			 print_r($this->rowData);
			 print_r($product->getData());
			 exit;
			 */

			unset($this->rowData);
			unset($this->data);

			if($product->getSku()!='') {
				$product->save();


				//Save Product Stoct Item.
				$stockItem = Mage::getModel('cataloginventory/stock_item');
				$stockItem->loadByProduct($product->getId());

				if (! $stockItem->getId()) {
					$stockItem->setProductId($product->getId())->setStockId(1);
					$stockItem->setProduct($product);
				}

				//$stockItem->setData('qty', 0);
				//$stockItem->setData('manage_stock', 1);
				/*
				 if($this->rowData['price']>0) {
				 $stockItem->setData('is_in_stock', 1);
				 }	else {
				 $stockItem->setData('is_in_stock', 0);
				 }
				 */

				$stockItem->setData('is_in_stock', $is_in_stock);
				$stockItem->save();
					
			}else {
				$this->setMessage('SKU is not valid!');
			}
			//p($this->rowData);

			unset($product);
			//unset($stockItem);
			return true;
		} catch (Exception $e) {
			$this->setMessage('Exception:'.$e->getMessage());
			return false;
		}

	}
	public function saveProduct()
	{
		Varien_Profiler::start('saveProduct');
		$flag = $this->processData();
		Varien_Profiler::stop('saveProduct');
		$msg = '';
		if($this->print_str == 'PreUpdated') {
			$status=1;
			//$msg = $this->print_str;
		} else if($flag) { //success
			$this->print_str = "Success";
			$msg = $this->writeLog();
			$status=1;
		}else { // fail
			$this->print_str = "Fail";
			$this->setMessage('Fail to Save Product');
			$msg = $this->writeLog();
			if(stristr($msg, 'SQLSTATE')) {
				$status = 0; //deadlock
			} else {
				$status=2; // fail
			}
		}
        
		if($this->print_str=='Success' || $this->print_str=='Fail') {
			$this->importLogRow->setData('estatus',$status);
			$this->importLogRow->setData('msg',$msg);
			$this->importLogRow->save();
		}
		return $status;
		//$this->con->query("UPDATE import_log SET estatus = '".$status."', msg = '".$msg."' WHERE sku = '".$this->sku."'");
	}
} // class ends